package com.tanhua.server.service;

import cn.hutool.captcha.CircleCaptcha;
import com.tanhua.common.pojo.Admin;
import com.tanhua.common.utils.AdminThreadLocal;
import com.tanhua.server.api.AdminService;
import com.tanhua.server.vo.AdminVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoadService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AdminService adminService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${jwt.secret}")// 盐值
    private String secret;

    /**
     * 登录成功，返回一个token
     *
     * @param username
     * @param password
     * @param verificationCode
     * @param uuid
     * @return
     */
    public String load(String username, String password, String verificationCode, String uuid) {
        //根据传递过来的uuid获取验证码code，如果是null说明过期
        String result = (String) redisTemplate.opsForValue().get(uuid);
        if (!StringUtils.isNotEmpty(result)) {
            log.info("验证码已过期");
            return null;
        }
        redisTemplate.delete(uuid);
        Admin admin = adminService.selectByUsernameAndPassword(username, password);
        //判断是否查到用户
        if (admin == null) {
            log.info("用户名或密码不正确");
            return null;
        }
        if (!result.equals(verificationCode)) {
            log.info("验证码错误");
            return null;
        }

        //生成token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("username", admin.getUsername());
        claims.put("id", admin.getId());

        String jwt = Jwts.builder()
                .setClaims(claims)//存放数据位置
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusDays(1).toDate())//设置一天过期
                .compact();

        //把用户id 和 token存到redis中，做登录校验的时候,
        // String redisKey = admin.getId()+"";
        //6String redisValue = "TOKEN"+jwt;


        //        try {
        //            //调用mq发送日志消息
        //            HashMap<String, Object> msg = new HashMap<>();
        //            msg.put("username",admin.getUsername());
        //            msg.put("date",System.currentTimeMillis());
        //            rocketMQTemplate.convertAndSend("tanhua-houtai-login",msg);
        //        } catch (MessagingException e) {
        //            log.error("发送消息失败",e);
        //        }

        return jwt;
    }

    /**
     * 生成验证码图片
     *
     * @return
     */
    public void getVerificationCode(String uuid, HttpServletResponse response) throws IOException {
        //调用hutool工具生成验证码，
        CircleCaptcha circleCaptcha = new CircleCaptcha(200, 100, 4, 20);
        //获取验证码里面的数据，存到redis中，key为uuid，value为code，过期时间60s
        String code = circleCaptcha.getCode();
        redisTemplate.opsForValue().set(uuid, code, 60, TimeUnit.MINUTES);
        ServletOutputStream outputStream = response.getOutputStream();
        circleCaptcha.write(outputStream);
    }

    /**
     * 查询用户信息
     *
     * @param token
     * @return
     */
    public AdminVo fillAdmin(String token) {
        //从线程里获取admin
        Admin admin = AdminThreadLocal.get();
        Long id = admin.getId();
        String username = admin.getUsername();
        String avatar = admin.getAvatar();
        AdminVo adminVo = new AdminVo();
        adminVo.setAvatar(avatar);
        adminVo.setUid(id + "");
        adminVo.setUsername(username);
        return adminVo;

    }

    public ResponseEntity<Void> layout(String token) {
        return ResponseEntity.ok(null);
    }
}